import { NextRequest, NextResponse } from 'next/server';
import sqlite3 from 'sqlite3';
import path from 'path';

const dbPath = path.join(process.cwd(), 'data', 'database.sqlite');

interface ContactInfo {
  id: string;
  type: 'wechat_group' | 'wechat_official' | 'qq_group' | 'email' | 'phone' | 'address';
  title: string;
  description?: string;
  content: string;
  qrCode?: string;
  isVisible: boolean;
  order: number;
}

// 初始化数据库表
const initializeDatabase = () => {
  return new Promise<sqlite3.Database>((resolve, reject) => {
    const db = new sqlite3.Database(dbPath, (err) => {
      if (err) {
        reject(err);
        return;
      }
      
      // 创建联系方式表
      db.run(`CREATE TABLE IF NOT EXISTS contacts (
        id TEXT PRIMARY KEY,
        type TEXT NOT NULL,
        title TEXT NOT NULL,
        description TEXT,
        content TEXT NOT NULL,
        qr_code TEXT,
        is_visible INTEGER DEFAULT 1,
        order_num INTEGER DEFAULT 1,
        created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
        updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
      )`, (err) => {
        if (err) {
          reject(err);
          return;
        }

        // 插入默认数据
        const defaultContacts = [
          {
            id: 'wechat-group-1',
            type: 'wechat_group',
            title: '技术交流群',
            description: '讨论机器人技术，分享学习资源',
            content: '扫码加入微信群',
            qr_code: '/api/uploads/wechat-group-qr.svg',
            is_visible: 1,
            order_num: 1
          },
          {
            id: 'wechat-official-1',
            type: 'wechat_official',
            title: '实验室公众号',
            description: '获取最新动态和技术文章',
            content: '关注我们的微信公众号',
            qr_code: '/api/uploads/wechat-official-qr.svg',
            is_visible: 1,
            order_num: 2
          },
          {
            id: 'email-1',
            type: 'email',
            title: '联系邮箱',
            description: '商务合作、学术交流',
            content: 'contact@roboticslab.com',
            qr_code: null,
            is_visible: 1,
            order_num: 3
          }
        ];

        // 检查是否已有数据
        db.get('SELECT COUNT(*) as count FROM contacts', (err, row: any) => {
          if (!err && row.count === 0) {
            const stmt = db.prepare(`INSERT OR IGNORE INTO contacts (id, type, title, description, content, qr_code, is_visible, order_num) VALUES (?, ?, ?, ?, ?, ?, ?, ?)`);
            
            defaultContacts.forEach(contact => {
              stmt.run([
                contact.id, 
                contact.type, 
                contact.title, 
                contact.description, 
                contact.content, 
                contact.qr_code, 
                contact.is_visible, 
                contact.order_num
              ]);
            });
            
            stmt.finalize();
          }
          resolve(db);
        });
      });
    });
  });
};

export async function GET(request: NextRequest) {
  try {
    const db = await initializeDatabase();
    
    return new Promise<NextResponse>((resolve, reject) => {
      db.all(`
        SELECT id, type, title, description, content, qr_code as qrCode, is_visible as isVisible, order_num as orderNum
        FROM contacts 
        WHERE is_visible = 1 
        ORDER BY order_num ASC
      `, (err, rows: any[]) => {
        db.close();
        
        if (err) {
          reject(err);
          return;
        }
        
        const contacts: ContactInfo[] = rows.map(row => ({
          id: row.id,
          type: row.type,
          title: row.title,
          description: row.description,
          content: row.content,
          qrCode: row.qrCode,
          isVisible: Boolean(row.isVisible),
          order: row.orderNum
        }));
        
        resolve(NextResponse.json({
          success: true,
          data: contacts
        }));
      });
    });
  } catch (error) {
    console.error('获取联系方式失败:', error);
    return NextResponse.json(
      { success: false, error: '获取联系方式失败' },
      { status: 500 }
    );
  }
}